const Koa =require('koa')
const app=new Koa();
const router=require('koa-router')()
const bodyparser=require('koa-bodyparser');
const connect = require('./db/index');

router.get('/list',async ctx=>
{
    let res=await new Promise((resolve,reject)=>
    {
        connect.query(`select * from login`,(err,data)=>
        {
            if(!err)
            {
                resolve(data)
            }
            else
            {
                reject('失败！')
            }
        })
    })
    ctx.body={
        code:0,
        mes:"list接口",
        data:res
    }
})
router.get('/delete',async ctx=>
{
    const {id}=ctx.query;
    let res=await new Promise((resolve,reject)=>
    {
        connect.query(`delete from login where id=${id}`,(err,data)=>
        {
            if(!err)
            {
                resolve(data)
            }
            else
            {
                reject('失败！')
            }
        })
    })
    ctx.body={
        code:0,
        mes:"delete接口",
        data:res
    }
})
router.post('/add',async ctx=>
{
    const {name,phone,pwd}=ctx.request.body;
    let res=await new Promise((resolve,reject)=>
    {
        connect.query(`insert into login (name,phone,pwd) values ('${name}','${phone}','${pwd}')`,(err,data)=>
        {
            if(!err)
            {
                resolve(data)
            }
            else
            {
                reject('失败！')
            }
        })
    })
    ctx.body={
        code:0,
        mes:"add接口",
        data:res
    }
})
router.post('/update',async ctx=>
{
    const {name,phone,pwd,id}=ctx.request.body;
    let res=await new Promise((resolve,reject)=>
    {
        connect.query(`update login set name='${name}',phone='${phone}',pwd='${pwd}' where id=${id}`,(err,data)=>
        {
            if(!err)
            {
                resolve(data)
            }
            else
            {
                reject('失败！')
            }
        })
    })
    ctx.body={
        code:0,
        mes:"update接口",
        data:res
    }
})
app.use(bodyparser())
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000)